<template>
  <div class="common-layout">
    <h1 class="title" style="text-align: center;font-size: 100px"> 欢迎参加考试</h1>
    <el-row gutter="20" style="margin-top: 100px">
      <!--身份栏-->
      <el-col :span="10">

        <el-card>
          <div class="examinee-info" style="display: flex;align-content: center;justify-content: center; font-weight: bold">
            <p>姓名：{{name}}</p>
            <p class="margin-left-30">考生号：{{userId}}</p>
          </div>
        <div class="note-points" >
          <p>注意事项：</p>
          <p>1、考试过程中请勿随意变更计算机。如确因计算机故障无法正常考试，需由监考人员操作才可更换。</p>
          <p>2、一旦参加某场考试，计时开始，请在规定的考试时间内完成考试。</p>
          <p>3、考试中途可以多次提交自己的源代码，以最后一次提交为准。</p>
          <p>4、如出现进入考试异常的情况，请报告监考老师。</p>
          <p>5、提交代码时请注意选择对应的程序设计语言，如因语言错误导致的判分有误，由考生自行承担责任。</p>
          <p>6、请勿在源代码内添加“system(“pause”)”之类的语句，导致超时该题会被判为0分。</p>
          <p>7、严禁在源代码内添加任何对系统有损害的调用，如发现此类代码，一律做0分处理。严重者将提交司法机关。</p>
          <p>8、点击下一题和上一题以及跳转题目类型的时候都会暂存答案，但是只有交卷时才会计分</p>
          <p>9、暂存代码没有评测，只有提交代码才会评测得分</p>
        </div>
        </el-card>
      </el-col>
      <el-col :span="14">
        <el-card>
          <div class="exam" style="margin:  auto">
            <!--过滤栏-->
            <div class="filter-container">
              <div class="filter-item item-input">
                <el-input v-model.trim="examParams.condition.examName" placeholder="请输入考试名称"></el-input>
              </div>
              <div class="filter-item item-button">
                <el-button type="primary" @click="searchExam"><i class="el-icon-search"></i> 搜索</el-button>
              </div>
              <div class="filter-item item-button">
                <el-button type="primary" @click="examParams.condition.examName = '',searchExam()"><i class="el-icon-refresh"></i> 刷新
                </el-button>
              </div>
            </div>
          </div>
          <div class="exam-list">
            <el-table
                v-loading="examLoading"
                :element-loading-svg="svg"
                class="custom-loading-svg"
                element-loading-svg-view-box="-10, -10, 50, 50"
                :data="examTables"
                border
                style="width: 100%;"
                :table-layout="auto">
              <el-table-column
                  label="序号"
                  width="60"
                  align="center">
                <template v-slot="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column
                  prop="examName"
                  label="考试名称"
                  width="100"
                  align="center">
              </el-table-column>
              <el-table-column
                  prop="classIdName"
                  label="考试班级"
                  width="100"
                  align="center">
              </el-table-column>
              <el-table-column
                  prop="companyIdName"
                  label="公司"
                  width="90"
                  align="center">
              </el-table-column>
              <el-table-column
                  prop="durationTime"
                  label="考试时长（分钟）"
                  width="100"
                  align="center">
              </el-table-column>
              <el-table-column
                  prop="startTime"
                  label="开考时间"
                  width="100"
                  align="center">
              </el-table-column>
              <el-table-column
                  prop="endTime"
                  label="结束时间"
                  width="100"
                  align="center">
              </el-table-column>
              <el-table-column
                  prop="languageType"
                  label="考试语言"
                  width="90"
                  align="center">
              </el-table-column>
              <el-table-column
                  prop="examType"
                  label="考试类型"
                  width="95"
                  align="center">
                <template v-slot="scope">
                  <el-tag v-if="scope.row.examType == 'TRAINING_EXAM'" type="success" disable-transitions>培训考试
                  </el-tag>
                  <el-tooltip content="该场考试正在考试中" placement="top">
                    <el-tag v-if="scope.row.examType == 'CERTIFICATION_EXAM'" type="info" disable-transitions>认证考试
                    </el-tag>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column
                  prop="examStatus"
                  label="考试状态"
                  width="95"
                  align="center">
                <template v-slot="scope">
                  <el-tag v-if="scope.row.examStatus == 'IN_EXAMINATION'" type="success" disable-transitions>考试中
                  </el-tag>
                  <el-tooltip content="该场考试正在考试中" placement="top">
                    <el-tag v-if="scope.row.examStatus == 'PRE_EXAM'" type="info" disable-transitions>未开考</el-tag>
                  </el-tooltip>
                  <el-tag v-if="scope.row.examStatus == 'OVER'" type="warning" disable-transitions>已结束</el-tag>
                  <el-tag v-if="scope.row.examStatus == '3'" type="danger" disable-transitions>阅卷中</el-tag>
                  <el-tooltip content="该场考试已完成阅卷" placement="top">
                    <el-tag v-if="scope.row.disabled == 4" disable-transitions>已阅卷</el-tag>
                  </el-tooltip>
                </template>
              </el-table-column>
              <!--<el-table-column-->
              <!--    prop="disabled"-->
              <!--    label="状态"-->
              <!--    width="80"-->
              <!--    align="center">-->
              <!--  <template v-slot="scope">-->
              <!--    <el-tag v-if="scope.row.disabled == true" type="warning" disable-transitions>启用</el-tag>-->
              <!--    <el-tag v-if="scope.row.disabled == false" type="danger" disable-transitions>弃用</el-tag>-->
              <!--  </template>-->
              <!--TODO 后面记得删掉-->
              <!--v-if="scope.row.examStatus == 'IN_EXAMINATION'"-->
              <el-table-column label="操作" width="100" align="center" >
                <template v-slot="scope">
                  <div class="button-container">
                    <el-button
                        size="small"
                        type="danger"
                        v-if="scope.row.examStatus == 'IN_EXAMINATION'"
                        @click="enterExam(scope.row)"
                        v-loading.fullscreen.lock="fullscreenLoading">
                    开始考试
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <el-pagination
              v-model:current-page="examParams.paging.pageIndex"
              v-model:page-size="examParams.paging.pageSize"
              :page-sizes="[5, 10, 20, 100]"
              :small="small"
              :disabled="disabled"
              :background="background"
              layout="total, sizes, prev, pager, next, jumper"
              v-model:total="examParams.paging.totalCount"
              @size-change="searchExam"
              @current-change="searchExam"
          />
        </el-card>
      </el-col>
    </el-row>


  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
// 例如：import  《组件名称》  from '《组件路径》 ';
import ExamApi from "@/api/Exam"
import CompanyApi from "@/api/company"
import {ElMessage} from "element-plus";
import store from "@/store";


export default {
  // import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    // 这里存放数据
    return {
      token: null,
      fullscreenLoading: false,
      errorTriggered: false,
      examParams: {
        extras: {},
        paging: {
          totalCount: 10,
          pageIndex: 1,
          pageSize: 100,
          enableTotalCount: true
        },
        sorts: null,
        condition: {
          paperId: null,
          examName: null,
          startTime: null,
          examStatus: null,
          endTime: null,
          classIds: null
        }
      },
      examTables: [],
      examLoading: false,

      //  所有公司
      AllCompany: [],
    }
  },
  // 计算属性 类似于 data 概念
  computed: {},
  // 监控 data 中的数据变化
  watch: {},
  // TODO 方法集合
  methods: {
    //  获得用户的所有考试

    async searchExam() {
      this.examLoading = true
      await ExamApi.getUserExam(this.examParams, this.token).then(async res => {
        this.examLoading = true
        if (res.data.success === true) {
          for (const exam of res.data.data) {

            if (exam.classId === null) {
              exam.classIdName = "无班级"
            } else {
              await ExamApi.getClassInfo(exam.classId, this.token).then(res => {
                if (res.data.success == true) {
                  if (res.data.data == null) {
                    exam.classIdName = "无班级信息"
                  } else {
                    exam.classIdName = res.data.data.className
                  }
                }
              })
            }
            if (exam.companyId === null) {
              exam.companyIdName = "无公司"
            } else {
              let conpanyFlag = false
              this.AllCompany.forEach(company => {
                if (exam.companyId == company.id) {
                  exam.companyIdName = company.name
                  conpanyFlag = true
                }
              })
              if (conpanyFlag == false) {
                exam.companyIdName = "未搜索到公司"
              }
            }
          }
          this.examTables = res.data.data
          console.log("YyyyYY")
          console.log(this.examTables)
          this.examParams.paging.totalCount = res.data.totalCount
          this.$message.success("获取考试信息成功")
          this.examLoading = false
        } else {
          this.$message.error("获取考试信息失败，请联系管理员")
        }
      }).catch(res => {
        this.$message.error(res)
      })
    },


    //获得所有公司
    getAllCompanyList() {
      CompanyApi.getAllCompany(this.token).then(res => {
        if (res.data.success == true) {
          this.AllCompany = res.data.content
        }
      }).catch(res => {
        this.$message(res)
      })
    },

    //  开始考试
    enterExam(param) {
      this.fullscreenLoading = true
      ExamApi.userEnterExam(param.id,this.token).then(res => {
        if (res.data.success == false && !this.errorTriggered) {
          console.log("3333333333333333")
          this.errorTriggered = true;  // 防止重复弹出
          this.$message.error(res.data.message)
        }else if(res.data.success==true){
          console.log(res.data.data)
          localStorage.setItem("examFlag","ing")
          localStorage.setItem("examPaper",JSON.stringify(res.data.data))
          localStorage.setItem("examId",param.id)
          localStorage.setItem("examName",param.examName)
          localStorage.setItem("examClassId",param.classId)
          localStorage.setItem("examTime", res.data.data.firstEnterTime)
          localStorage.setItem("examEndTime", res.data.data.endTime)
          localStorage.setItem("examDurationTime",res.data.data.durationTime)
          localStorage.setItem("examLanguageType",res.data.data.languageType)
          if(res.data.data.delayTime!=null){
            localStorage.setItem("examDelayTime",res.data.data.delayTime)
          }else {
            localStorage.setItem("examDelayTime","false")
          }
          // const examTimeToken = localStorage.getItem( "examTime")
          //const durationTimeToken = localStorage.getItem("examDurationTime")
          let examDelayFlag =  localStorage.getItem("examDelayTime")
          // const examTime = new Date(examTimeToken)
          if(examDelayFlag=="false"){
            examDelayFlag=0
          }
          // const durationMillis = durationTimeToken * 60 * 60 * 1000+examDelayFlag*60*1000; // 持续时间转换为毫秒
          // const targetTime = new Date(examTime.getTime() + durationMillis); // 计算目标时间
          const examEndTime = localStorage.getItem("examEndTime");
          const currentTime = new Date(); // 获取当前时间的Date对象
          localStorage.setItem("examEnterTime",currentTime)
          console.log(currentTime)
          //console.log("timeDiff" , timeDiff)// 计算目标时间和当前时间的时间差（单位：毫秒）
          if (examEndTime <= currentTime) {
            this.$message.error("你的考试时间已过，若想重新进入考场，请联系培训老师")

          }else {
            store.commit('user/loginOut')
            this.$router.push({name:"ShowTest"});

          }

        }
        this.fullscreenLoading = false;
      }).catch(res=>{
        // console.log(res,"!!!!!!!!")
        // this.$message.error(res.response.data.message)
      })
    },

    //检查是否全屏






},

  // 生命周期 - 创建完成（可以访问当前this 实例）
  setup() {
  },
  //TODO 挂载
  mounted() {
    this.token = localStorage.getItem('token')
    this.searchExam()
    // 检查浏览器是否全屏
    // 组件挂载后，检查全屏状态
    // this.checkFullScreen();

    // 添加全屏改变事件监听器
    // document.addEventListener('fullscreenchange', this.checkFullScreen);


    this.getAllCompanyList()
  },

  // beforeRouteLeave(to, from, next) {
  //   // 在离开该组件时检测路由变化
  //   this.$message.error('警告：即将离开该组件，导航到', to.path);
  //   next(); // 必须调用 next() 方法来解析这个钩子
  // },
// 生命周期 - 挂载完成（可以访问 DOM 元素）
  onMounted() {
  },
  onBeforeMount() {
  }, // 生命周期 - 挂载之前
  onBeforeUpdate() {
  }, // 生命周期 - 更新之前
  onUpdated() {
  }, // 生命周期 - 更新之后
  onBeforeUnmount() {

  }, // 生命周期 - 销毁之前
  onUnmounted() {
    // 移除全屏检测事件监听器
    // window.removeEventListener('resize');
  }, // 生命周期 - 销毁完成
  onErrorCaptured() {
  } // 如果页面有 keep-alive 缓存功能,这个函数会触发
}
</script>

<style scoped>
.filter-container {
  padding-bottom: 10px;
}

.filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
}

.item-input {
  width: 200px;
  margin-right: 5px;
}

.filter-container .filter-item:nth-child(3), .filter-container .filter-item:nth-child(4) {
  margin-left: 16px;
}

.exam-list {
  width: 100%;
}
.title{
  color: #fafafa;
  letter-spacing: 0;
  text-shadow: 0px 1px 0px #999, 0px 2px 0px #888, 0px 3px 0px #777, 0px 4px 0px #666, 0px 5px 0px #555, 0px 6px 0px #444, 0px 7px 0px #333, 0px 8px 7px #001135;
}

</style>
